package com.shankungfu.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.CommentAdapter;
import com.shankungfu.bean.ActivityReplyBean;
import com.shankungfu.bean.ReplyBean;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;

public class CommentActivity extends Activity implements OnClickListener,
		OnItemClickListener,OnScrollListener {
	public static final int SUCCESS_CODE = 1000;
	public static final int DENGLU_SUCCESS_CODE = 1001;

	public static final String PROJECT_ID = "PROJECT_ID";

	private static final int DATA_SUCCESS = 1;

	private RelativeLayout progressBar;
	private ImageView head_refresh;
	private ImageView head_goback;
	private ImageView iv;
	private TextView detail_title;
	private String project_id = "0";
	private List<ReplyBean> replyBeanList;
	private CommentAdapter adapter;
	private ListView commentListView;
	private int pagesize = 1; //当前分页数
	private int visibleLastIndex = 0; //最后的可视项索引
	private int visibleItemCount; // 当前窗口可见项总数
	private View loadMoreView;
	private Button loadMoreButton;
	private ProgressBar loadMoreProgressBar;
	private ActivityReplyBean activityReplyBean;
	private LayoutInflater mInflater;
	private boolean isbackResult = false;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case DATA_SUCCESS:
				ActivityReplyBean activityReplyBean = (ActivityReplyBean) msg.obj;
				replyBeanList = activityReplyBean.getReplyListData();
				if(isbackResult){
					adapter.setData(replyBeanList);
				} else {
					adapter.addData(replyBeanList);
				}
				if(!activityReplyBean.isNext() && replyBeanList == null){
					loadMoreProgressBar.setVisibility(View.GONE);
					loadMoreButton.setText("当前项目没有评论");
					
				} else if(activityReplyBean.isNext()){
					commentListView.setSelection(visibleLastIndex - visibleItemCount + 1); //设置选中项
		            loadMoreButton.setText("加载更多评论");    //恢复按钮文字 
				} else {
					loadMoreProgressBar.setVisibility(View.GONE);
					loadMoreButton.setText("评论加载完毕");
				}
				break;

			default:
				break;
			}
			adapter.notifyDataSetChanged();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.comment_layout);

		init();
		updateForData();
		getData(pagesize);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == SUCCESS_CODE) {
			updateForData();
			isbackResult = true;
			getData(pagesize);
		} else if (resultCode == DENGLU_SUCCESS_CODE) {
			Intent intent = new Intent(this, PublishCommentActivity.class);
			intent.putExtra(PROJECT_ID, project_id);
			startActivityForResult(intent, SUCCESS_CODE);
		}
	}

	private void init() {
		project_id = getIntent().getStringExtra("project_id");
		replyBeanList = new ArrayList<ReplyBean>();

		progressBar = (RelativeLayout) findViewById(R.id.comment_progressBar);
		commentListView = (ListView) findViewById(R.id.comment_listview);
		head_refresh = (ImageView) findViewById(R.id.head_refresh);
		head_goback = (ImageView) findViewById(R.id.head_goback);
		iv = (ImageView) findViewById(R.id.iv);
		detail_title = (TextView) findViewById(R.id.detail_title);

		head_refresh.setImageResource(R.drawable.eidt_image);

		detail_title.setText("评论");
		
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		loadMoreView = mInflater.inflate(R.layout.loadmore_layout, null);  
	    loadMoreButton = (Button) loadMoreView.findViewById(R.id.loadmore_btn);
	    loadMoreProgressBar = (ProgressBar) loadMoreView.findViewById(R.id.loadmore_progressbar);
	    
	    commentListView.addFooterView(loadMoreView);   //设置列表底部视图
		
		adapter = new CommentAdapter(CommentActivity.this,
				MainApplication.getOptions());
		commentListView.setAdapter(adapter);

		commentListView.setOnScrollListener(this);
		head_goback.setOnClickListener(this);
		commentListView.setOnItemClickListener(this);
	}

	private void getData(int pagesize) {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "activityreply");
		params.add("app_info", "shankungfu");
		params.add("activity_id", project_id);
		params.add("page", String.valueOf(pagesize));

		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					activityReplyBean = JSON.parseObject(
							content, ActivityReplyBean.class);

					Message msg = new Message();
					msg.what = DATA_SUCCESS;
					msg.obj = activityReplyBean;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onFailure(String content) {
			}
		};
		httpclient.request(GlobleConstant.ACTIVITY_REPLY, params,
				responseHandler);
	}

	private void updateForData() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void getSuccessData() {
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.head_goback:
			finishActivity();
			break;

		case R.id.head_refresh:

			if (MainApplication.isUserIsLogin()) {
				Intent intent = new Intent(this, PublishCommentActivity.class);
				intent.putExtra(PROJECT_ID, project_id);
				startActivityForResult(intent, SUCCESS_CODE);
			} else {
				ToastUtil.showMessageText(this, "请先登录");
				Intent intent = new Intent(this, LogInActivity.class);
				startActivityForResult(intent, DENGLU_SUCCESS_CODE);
			}
			break;
		}
	}

	private void finishActivity() {
		// setResult(PickItemDetailActivity.SUCCESS_CODE);
		finish();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// 点击某个评论
		ReplyBean replyBean = adapter.getItem(position);
		Intent intent = new Intent(this, CommentReplyActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString("reply_id", replyBean.getReply_id());
		bundle.putString("author", replyBean.getReply_user_name());
		bundle.putString("date", replyBean.getReply_time());
		bundle.putString("content", replyBean.getReply_content());
		bundle.putString("image", replyBean.getReply_avatar_img());
		intent.putExtra("replyBean", bundle);
		startActivity(intent);
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;  
	    visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		int itemsLastIndex = adapter.getCount() - 1;    //数据集最后一项的索引   
	    int lastIndex = itemsLastIndex + 1;             //加上底部的loadMoreView项   
	    
	    if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {  
	        //如果是自动加载,可以在这里放置异步加载数据的代码   
	        Log.i("LOADMORE", "loading...");
	        ++pagesize;
	        isbackResult = false;
	        getData(pagesize);
	    } else {
	    	loadMoreProgressBar.setVisibility(View.GONE);
//			loadMoreButton.setVisibility(View.GONE);
		}
	}
}
